package org.example;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        try {
            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();
            Request request = new Request(in);
            Response response = new Response(out);
            System.out.println(request);
            HttpServlet httpServlet = servletMap.get(request.getUrl());
            if (httpServlet == null) {
                //静态资源处理
                response.outputHtml(request.getUrl());
            } else {
                httpServlet.service(request, response);
                // 动态资源servlet请求
            }
            socket.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
